import router from '../router';
export default async (url = '', data = {}, type = 'POST', method = 'fetch') => {
    type = type.toUpperCase()
    if (type === 'GET') {
        let dataStr = ''
        Object.keys(data).forEach(key => {
            dataStr += `${key}=${data[key]}&`
        })
        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'))
            url = `${url}?${dataStr}`
        }
    }
    if (window.fetch && method === 'fetch') {
        let requestConfig = {
            // credentials: 'include', //include,表示无论跨域还是同源请求都会带cookie
            method: type,
            headers: {
                'Accept': 'application/json;charset=UTF-8',
                'Content-Type': 'application/json;charset=UTF-8',
                'token': localStorage.getItem('token')
            },
            mode: 'cors', //cors: 表示同域和带有CORS响应头的跨域下可请求成功. 其他请求将被拒绝.
            cache: 'default' //表示fetch请求之前将检查下http的缓存.
        }
        if (type === 'POST') {
            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            })
        }
        try {
            const response = await fetch(url, requestConfig)
            const responseJson = response.json()
            responseJson.then(result=>{
                console.log(result)
                if(result.code == 404){
                    router.push("/login")
                    return false
                }
            })
            return responseJson
        } catch (error) {
            throw new Error(error)
        }
    } else {
        return new Promise((resolve, reject) => {
            let requestObj
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest()
            } else {
                let ActiveObject = window.ActiveObject
                requestObj = new ActiveObject()
            }

            let sendData = ''
            if (type === 'POST') {
                sendData = JSON.stringify(data)
            }
            request.open(type, url, true)
            request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
            requestObj.send(sendData)

            requestObj.onreadystatechange = () => {
                if (requestObj.readyState === 4) {
                    if (requestObj.status === 200) {
                        let obj = requestObj.response
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj)
                        }
                        resolve(obj)
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
}